import requests
import json
import logging
from urllib.parse import urlencode
from django.conf import settings

class EbayAuthService:
    """eBay授权服务类"""
    
    # eBay API 端点
    EBAY_AUTH_URL = "https://auth.ebay.com/oauth2/authorize"
    EBAY_TOKEN_URL = "https://api.ebay.com/identity/v1/oauth2/token"
    EBAY_SANDBOX_AUTH_URL = "https://auth.sandbox.ebay.com/oauth2/authorize"
    EBAY_SANDBOX_TOKEN_URL = "https://api.sandbox.ebay.com/identity/v1/oauth2/token"

    # eBay API 所需权限范围
    EBAY_SCOPES = [
        'https://api.ebay.com/oauth/api_scope',
        'https://api.ebay.com/oauth/api_scope/sell.inventory',
        'https://api.ebay.com/oauth/api_scope/sell.marketing',
        'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
        'https://api.ebay.com/oauth/api_scope/sell.finances',
        'https://api.ebay.com/oauth/api_scope/sell.fulfillment'
    ]

    def __init__(self, is_sandbox=False):
        """
        初始化eBay授权服务
        
        Args:
            is_sandbox (bool): 是否使用沙箱环境
        """
        self.is_sandbox = is_sandbox
        self.auth_url = self.EBAY_SANDBOX_AUTH_URL if is_sandbox else self.EBAY_AUTH_URL
        self.token_url = self.EBAY_SANDBOX_TOKEN_URL if is_sandbox else self.EBAY_TOKEN_URL
        self.client_id = settings.EBAY_CLIENT_ID
        self.client_secret = settings.EBAY_CLIENT_SECRET
        self.redirect_uri = settings.EBAY_REDIRECT_URI

    def get_auth_url(self, state):
        """
        生成eBay授权URL
        
        Args:
            state (str): 状态参数，用于防止CSRF攻击
            
        Returns:
            str: 授权URL
        """
        params = {
            'client_id': self.client_id,
            'response_type': 'code',
            'redirect_uri': self.redirect_uri,
            'scope': ' '.join(self.EBAY_SCOPES),
            'state': state
        }
        return f"{self.auth_url}?{urlencode(params)}"

    def get_access_token(self, code):
        """
        使用授权码获取访问令牌
        
        Args:
            code (str): 授权码
            
        Returns:
            dict: 包含访问令牌和刷新令牌的字典
            
        Raises:
            requests.exceptions.RequestException: 请求失败时抛出
        """
        data = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': self.redirect_uri
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        auth = (self.client_id, self.client_secret)

        try:
            response = requests.post(self.token_url, data=data, headers=headers, auth=auth)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            logging.error(f"获取eBay访问令牌失败: {str(e)}")
            raise

    def refresh_access_token(self, refresh_token):
        """
        刷新访问令牌
        
        Args:
            refresh_token (str): 刷新令牌
            
        Returns:
            dict: 包含新的访问令牌和刷新令牌的字典
            
        Raises:
            requests.exceptions.RequestException: 请求失败时抛出
        """
        data = {
            'grant_type': 'refresh_token',
            'refresh_token': refresh_token,
            'scope': ' '.join(self.EBAY_SCOPES)
        }
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        auth = (self.client_id, self.client_secret)

        try:
            response = requests.post(self.token_url, data=data, headers=headers, auth=auth)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            logging.error(f"刷新eBay访问令牌失败: {str(e)}")
            raise 